﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Sonce.Common
{
    /// <summary>
    /// Reference: http://www.cameronalbert.com/post/2008/03/HttpWebRequest-Helper-for-Silverlight-2.aspx
    /// </summary>
    public partial class HttpHelper
    {
        #region Constructor
        /// <summary>
        /// Initializes a new HttpHelper instance.
        /// </summary>
        public HttpHelper()
        {
        }
        #endregion

        #region Public properties
        /// <summary>
        /// Gets a value indicating whether the downloading is progress - request has been sent but response not yet received.
        /// </summary>
        public bool DownloadInProgess
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets a raw UTF8 string for upload.
        /// </summary>
        public string UploadString
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets a HttpWebRequest object.
        /// </summary>
        public HttpWebRequest Request
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets a HttpWebResponse object.
        /// </summary>
        public HttpWebResponse Response
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets a list of POST variables.
        /// </summary>
        public Dictionary<string, string> PostValues
        {
            get;
            private set;
        }
        #endregion

        #region Private methods
        private void beginRequest(IAsyncResult ar)
        {
            try
            {
                using (StreamWriter writer = new StreamWriter(this.Request.EndGetRequestStream(ar)))
                {
                    if (this.UploadString != null)
                    {
                        //Upload raw string content
                        writer.Write(this.UploadString);
                    }
                    else
                    {
                        //Upload url encoded post variables
                        foreach (var item in this.PostValues)
                        {
                            //NOTE: Encoder must mask '=' char with something else
                            //writer.Write("{0}={1}&", item.Key, item.Value);
                            //writer.Write("{0}={1}&", item.Key, HttpUtility.UrlEncode(item.Value));
                            writer.Write("{0}={1}&", item.Key, Convert.ToBase64String(Encoding.UTF8.GetBytes(item.Value)));
                        }
                    }
                }
                this.Request.BeginGetResponse(new AsyncCallback(this.beginResponse), null);
            }
            catch (Exception ex)
            {
                OnDownloadStringCompleted(new HttpHelperEventArgs(ex));
            }
        }

        private void beginResponse(IAsyncResult ar)
        {
            string result = null;
            Exception error = null;

            try
            {
                this.Response = (HttpWebResponse)this.Request.EndGetResponse(ar);
                if (this.Response != null)
                {
                    //Read all content and trigger Completed event
                    Stream stream = this.Response.GetResponseStream();
                    if (stream != null)
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            result = reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex;
            }
            finally
            {
                //Notify completed
                HttpHelperEventArgs e = new HttpHelperEventArgs();
                e.Result = result;
                e.Error = error;
                e.ResponseUri = (this.Response != null ? this.Response.ResponseUri : null);
                OnDownloadStringCompleted(e);
            }
        }
        #endregion

        #region Public methods
        /// <summary>
        /// Download a string asynchronously.
        /// </summary>
        /// <param name="uri">Uri to a ASP, PHP or other script.</param>
        /// <param name="args">List of request POST variables.</param>
        public void DownloadStringAsync(Uri uri, Dictionary<string, string> args)
        {
            if (this.DownloadInProgess)
            {
                throw new Exception("Download is in progess, please wait until completed (see HttpHelper.DownloadInProgess property).");
            }

            this.DownloadInProgess = true;
            this.UploadString = null;
            this.PostValues = args;
            this.Response = null;
            this.Request = (HttpWebRequest)WebRequest.Create(uri);
            this.Request.ContentType = "application/x-www-form-urlencoded";
            this.Request.Method = "POST";
            //this.Request.Accept = "application/octetstream";
            this.Request.BeginGetRequestStream(new AsyncCallback(beginRequest), null);
        }

        /// <summary>
        /// Download a string asynchronously.
        /// </summary>
        /// <param name="uri">Uri to a ASP, PHP or other script.</param>
        /// <param name="upload">Raw UTF8 string for requets (upload).</param>
        public void DownloadStringAsync(Uri uri, string upload)
        {
            if (this.DownloadInProgess)
            {
                throw new Exception("Download is in progess, please wait until completed (see HttpHelper.DownloadInProgess property).");
            }

            this.DownloadInProgess = true;
            this.UploadString = upload;
            this.PostValues = null;
            this.Response = null;
            this.Request = (HttpWebRequest)WebRequest.Create(uri);
            this.Request.ContentType = "application/x-www-form-urlencoded";
            this.Request.Method = "POST";
            //this.Request.Accept = "application/octetstream";
            this.Request.BeginGetRequestStream(new AsyncCallback(beginRequest), null);
        }

        public void UploadStreamAsync(Uri uri, Stream stream)
        {
            string value = Utils.ReadStream(stream);
            if (!string.IsNullOrEmpty(value))
            {
                DownloadStringAsync(uri, value);
            }
        }
        #endregion

        #region Bubble events
        public event EventHandler<HttpHelperEventArgs> DownloadStringCompleted;
        protected virtual void OnDownloadStringCompleted(HttpHelperEventArgs e)
        {
            this.DownloadInProgess = false;
            if (DownloadStringCompleted != null)
            {
                DownloadStringCompleted(this, e);
            }
        }
        #endregion
    }

    public class HttpHelperEventArgs : EventArgs
    {
        #region Properties
        public string Result
        {
            get;
            set;
        }

        public Exception Error
        {
            get;
            set;
        }

        public Uri ResponseUri
        {
            get;
            set;
        }
        #endregion

        #region Constructors
        public HttpHelperEventArgs()
        {
        }

        public HttpHelperEventArgs(Exception ex)
        {
            this.Error = ex;
        }

        public HttpHelperEventArgs(string response, Exception ex, Uri responseUri)
        {
            this.Error = ex;
            this.Result = response;
            this.ResponseUri = responseUri;
        }
        #endregion
    }
}
